const ArticleModel = require('../../model/ArticleModel');
const ArticleCommentModel = require('../../model/ArticleComment');
const CategoryModel = require('../../model/CategoryModel');
const TagModel = require('../../model/TagModel');
const UserModel = require('../../model/UserModel');

const communityService = {
    getList: async (skip, limit, { keyword, category, sort } = {}) => {
        const query = { isDelete: false, isPublish: true };
        if (keyword) {
            query.$or = [
                { title: new RegExp(keyword, 'i') },
                { desc: new RegExp(keyword, 'i') }
            ];
        }
        if (category && category !== 'all') {
            query.categoryID = category;
        }
        const sortMap = {
            latest: { createTime: -1 },
            hot: { viewNum: -1 },
            recommend: { isRecommend: -1, createTime: -1 },
        };
        const sortOption = sortMap[sort] || { createTime: -1 };

        const data = await ArticleModel.find(query)
            .sort(sortOption)
            .skip(skip)
            .limit(limit)
            .lean();
        const total = await ArticleModel.countDocuments(query);

        // 处理关联数据
        for (let item of data) {
            // 处理封面图片
            if (item.cover) {
                item.cover = process.env.SERVER_BASE_URL + item.cover;
            }
            
            // 查询分类信息
            const category = await CategoryModel.findById(item.categoryID);
            
            // 查询作者信息
            const user = await UserModel.findById(item.authorID);
            
            // 处理标签信息
            let tags = [];
            if (item.tags && item.tags.length > 0) {
                const tagID = item.tags[0].split(",");
                const tagData = await TagModel.find({ _id: { $in: tagID } });
                tags = tagData.map(tag => ({
                    ...tag.toObject(),
                    icon: process.env.SERVER_BASE_URL + tag.icon
                }));
            }
            
            // 组装作者信息
            const authorInfo = {
                _id: user?._id || item.authorID,
                nickname: user?.nickname || '未知用户',
                avatar: user?.avatar ? process.env.SERVER_BASE_URL + user.avatar : null,
            };
            
            // 更新冗余存储的author字段
            item.author = authorInfo;
            
            // 组装关联信息
            item.aboutInfo = {
                category,
                user: {
                    name: authorInfo.nickname,
                    avatar: authorInfo.avatar,
                }
            };
            item.tags = tags;
            item.content = ""; // 列表不返回完整内容
        }

        return { data, total };
    },

    getDetail: async (id) => {
        const article = await ArticleModel.findOne({ _id: id, isDelete: false }).lean();
        if (!article) return null;

        // 处理封面图片
        if (article.cover) {
            article.cover = process.env.SERVER_BASE_URL + article.cover;
        }
        
        // 查询分类信息
        const category = await CategoryModel.findById(article.categoryID);
        
        // 查询作者信息
        const user = await UserModel.findById(article.authorID);
        
        // 处理标签信息
        let tags = [];
        if (article.tags && article.tags.length > 0) {
            const tagID = article.tags[0].split(",");
            const tagData = await TagModel.find({ _id: { $in: tagID } });
            tags = tagData.map(tag => ({
                ...tag.toObject(),
                icon: process.env.SERVER_BASE_URL + tag.icon
            }));
        }
        
        // 组装作者信息
        const authorInfo = {
            _id: user?._id || article.authorID,
            nickname: user?.nickname || '未知用户',
            avatar: user?.avatar ? process.env.SERVER_BASE_URL + user.avatar : null,
        };
        
        // 更新冗余存储的author字段
        article.author = authorInfo;
        
        // 组装关联信息
        article.aboutInfo = {
            category,
            author: authorInfo.nickname,
            tags: tags
        };
        
        return article;
    },

    addView: async (id) => {
        await ArticleModel.updateOne({ _id: id }, { $inc: { viewNum: 1 } });
    },

    // 根据ID获取文章（用于验证文章是否存在）
    getArticleById: async (id) => {
        return await ArticleModel.findOne({ _id: id, isDelete: false, isPublish: true }).lean();
    },

    like: async (id) => {
        await ArticleModel.updateOne({ _id: id }, { $inc: { likeNum: 1 } });
    },

    getRecommend: async (limit = 6) => {
        const data = await ArticleModel.find({ isDelete: false, isPublish: true, isRecommend: true })
            .sort({ createTime: -1 })
            .limit(limit)
            .lean();

        // 处理关联数据
        for (let item of data) {
            if (item.cover) {
                item.cover = process.env.SERVER_BASE_URL + item.cover;
            }
            
            const category = await CategoryModel.findById(item.categoryID);
            const user = await UserModel.findById(item.authorID);
            
            let tags = [];
            if (item.tags && item.tags.length > 0) {
                const tagID = item.tags[0].split(",");
                const tagData = await TagModel.find({ _id: { $in: tagID } });
                tags = tagData.map(tag => ({
                    ...tag.toObject(),
                    icon: process.env.SERVER_BASE_URL + tag.icon
                }));
            }
            
            // 组装作者信息
            const authorInfo = {
                _id: user?._id || item.authorID,
                nickname: user?.nickname || '未知用户',
                avatar: user?.avatar ? process.env.SERVER_BASE_URL + user.avatar : null,
            };
            
            // 更新冗余存储的author字段
            item.author = authorInfo;
            
            item.aboutInfo = {
                category,
                user: {
                    name: authorInfo.nickname,
                    avatar: authorInfo.avatar,
                }
            };
            item.tags = tags;
            item.content = "";
        }

        return data;
    },

    getHot: async (limit = 6) => {
        const data = await ArticleModel.find({ isDelete: false, isPublish: true })
            .sort({ viewNum: -1 })
            .limit(limit)
            .lean();

        // 处理关联数据
        for (let item of data) {
            if (item.cover) {
                item.cover = process.env.SERVER_BASE_URL + item.cover;
            }
            
            const category = await CategoryModel.findById(item.categoryID);
            const user = await UserModel.findById(item.authorID);
            
            let tags = [];
            if (item.tags && item.tags.length > 0) {
                const tagID = item.tags[0].split(",");
                const tagData = await TagModel.find({ _id: { $in: tagID } });
                tags = tagData.map(tag => ({
                    ...tag.toObject(),
                    icon: process.env.SERVER_BASE_URL + tag.icon
                }));
            }
            
            // 组装作者信息
            const authorInfo = {
                _id: user?._id || item.authorID,
                nickname: user?.nickname || '未知用户',
                avatar: user?.avatar ? process.env.SERVER_BASE_URL + user.avatar : null,
            };
            
            // 更新冗余存储的author字段
            item.author = authorInfo;
            
            item.aboutInfo = {
                category,
                user: {
                    name: authorInfo.nickname,
                    avatar: authorInfo.avatar,
                }
            };
            item.tags = tags;
            item.content = "";
        }

        return data;
    },

    search: async (keyword) => {
        const query = {
            isDelete: false,
            isPublish: true,
            $or: [
                { title: new RegExp(keyword, 'i') },
                { desc: new RegExp(keyword, 'i') },
            ],
        };
        const data = await ArticleModel.find(query).sort({ createTime: -1 }).lean();

        // 处理关联数据
        for (let item of data) {
            if (item.cover) {
                item.cover = process.env.SERVER_BASE_URL + item.cover;
            }
            
            const category = await CategoryModel.findById(item.categoryID);
            item.aboutInfo = category;
        }

        return data;
    },

    getCommentList: async (postId, skip, limit) => {
        const data = await ArticleCommentModel.find({ articleID: postId })
            .sort({ createTime: -1 })
            .skip(skip)
            .limit(limit)
            .lean();
        const total = await ArticleCommentModel.countDocuments({ articleID: postId });
        return { data, total };
    },

    addComment: async (payload) => {
        const articleId = payload.postId || payload.articleID;
        const result = await ArticleCommentModel.create({
            ...payload,
            articleID: articleId, // 统一字段名
            createTime: new Date(),
        });
        await ArticleModel.updateOne({ _id: articleId }, { $inc: { commentNum: 1 } });
        return result;
    },

    // 获取统计数据
    getStatistics: async () => {
        const totalPosts = await ArticleModel.countDocuments({ isDelete: false, isPublish: true });
        const totalComments = await ArticleCommentModel.countDocuments({});
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        const todayPosts = await ArticleModel.countDocuments({ 
            isDelete: false, 
            isPublish: true,
            createTime: { $gte: today } 
        });
        const todayComments = await ArticleCommentModel.countDocuments({ 
            createTime: { $gte: today } 
        });
        
        return {
            totalPosts,
            totalComments,
            todayPosts,
            todayComments,
            totalViews: await ArticleModel.aggregate([
                { $match: { isDelete: false, isPublish: true } },
                { $group: { _id: null, total: { $sum: '$viewNum' } } }
            ]).then(result => result[0]?.total || 0)
        };
    },

    // 获取分类列表
    getCategories: async () => {
        const categories = await ArticleModel.aggregate([
            { $match: { isDelete: false, isPublish: true } },
            { $group: { _id: '$categoryID', count: { $sum: 1 } } },
            { $sort: { count: -1 } }
        ]);
        
        return categories.map(cat => ({
            name: cat._id,
            count: cat.count
        }));
    },
};

module.exports = communityService;


